<template>
  <!-- :visible.sync="dialogVisible"
  等效于:visible="dialogVisible" @update:visible="dialogVisible = $event"
   -->
  <el-dialog
    :title="form.id?'编辑部门':'新增部门'"
    :visible="dialogVisible"
    width="50%"
    @close="onClose"
  >
    <!-- 通过emmet语法快速生成dom结构 -->
    <!-- el-form>(el-form-item[label]>el-input{})*4 -->
    <el-form ref="formRef" label-width="110px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="1-50个字符"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="1-50个字符"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:100%;">
          <el-option v-for="(item, index) in employeesList" :key="index" :label="item.username" :value="item.username"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" placeholder="1-300个字符"></el-input>
      </el-form-item>
    </el-form>

    <el-row slot="footer" type="flex" justify="center">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSumit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees.js'
import { addDepartment, getDepartmentDetail, getDepartments, updateDepartment } from '@/api/departments'
export default {
  name: 'AddDept',
  components: {},
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    // 新增-父部门
    node: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      // 分析,当前部门在同级部门中禁止出现重复部门
      // 数据来源
      //    父部门,通过父子组件传参传到子组件当中,即this.node
      //    所有的部门,发请求获取所有部门,即(await getDepartments()).depts
      //    同级部门,就是兄弟部门,找兄弟部门先得到父部门,根据父部门找兄弟,根据父部门id来全面部门当中找
      //       (await getDepartments()).depts.filter(t=>t.pid === this.node.id)
      //    当前部门,this.form.name或者value
      const allDepartments = (await getDepartments()).depts
      let brothers
      if (this.form.id) {
        // 编辑
        brothers = allDepartments.filter(t => t.id !== this.form.id && t.pid === this.form.pid)
      } else {
        // 新增
        brothers = allDepartments.filter(t => t.pid === this.node.id)
      }

      if (brothers.some(t => t.name === value)) {
        // 校验失败
        callback(new Error('同级部门中禁止出现重复部门'))
      } else {
        // 校验成功
        callback()
      }
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      // 分析,部门编码在整个模块中都不允许重复
      // 数据来源:
      //    部门编码,就是输入的部门编码,即this.form.code或者value
      //    整个模块中,就是所有的部门,发请求获取所有部门,即await getDepartments()
      //    不允许重复,就是在数组当中查找是否存在,find,findIndex,filter,some
      let allDepartments = (await getDepartments()).depts
      console.log(this.form.id, value, allDepartments)
      if (this.form.id) {
        allDepartments = allDepartments.filter(t => t.id !== this.form.id)
      }
      /*
      let isValid
      if (this.form.id) {
        // 编辑,排查当前部门
        isValid = allDepartments.filter(t => t.id !== this.form.id).some(t => t.code === value)
      } else {
        // 新增
        isValid = allDepartments.some(t => t.code === value)
      }
      */
      if (allDepartments.some(t => t.code === value)) {
        // 校验失败
        callback(new Error('部门编码在整个模块中都不允许重复'))
      } else {
        // 校验成功
        callback()
      }
    }
    return {
      // 绑定数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employeesList: [],
      rules: {
        // 部门名称（name）：必填 1-50个字符 / 同级部门中禁止出现重复部门
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        // 部门编码（code）：必填 1-50个字符 / 部门编码在整个模块中都不允许重复
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]

      }
    }
  },
  async created() {
    this.employeesList = await getEmployeesSimple()
  },
  mounted() {},
  methods: {
    async getDepartmentDetail(id) {
      this.form = await getDepartmentDetail(id)
    },
    async onSumit() {
      try {
        // 确保表单校验成功
        await this.$refs.formRef.validate()
        // 发请求
        if (this.form.id) {
          // 编辑
          updateDepartment(this.form)
        } else {
          // 新增
          await addDepartment({
            ...this.form,
            pid: this.node.id
          })
        }
        // 提示成功
        this.$message.success('操作成功')
        // 关闭对话框
        this.onClose()
        // 刷新列表
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    onClose() {
      // this.$emit('update-dialog-visible')
      // 重置表单
      //   对整个表单进行重置，将所有字段值重置为初始值
      //     所有字段,不对,是el-form-item配置了prop的字段
      //     初始值,第一次打开对话框的时候字段值
      //   移除校验结果
      //      删除红颜色错误提示
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$refs.formRef.resetFields()
      // 关闭对话框
      this.$emit('update:dialogVisible', false)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
